package com.example.homework3.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 统计 servlet处理请求的总花费时间
 */
@WebFilter("/*")
public class ProcessingTimeFilter extends HttpFilter {


    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        /*获取开始时间 */
        long service_start = System.currentTimeMillis();
        /*放行动作*/
        chain.doFilter(req, res);
        /*获取结束时间 */
        long service_stop = System.currentTimeMillis();
        /*获取请求进程时长*/
        long serviceTime = (service_stop - service_start);
        /*获取请求路径*/
        String path = req.getRequestURI();
        /*打印日志 */
        req.getServletContext().log("Time taken to process request for:" + path + " is:" + serviceTime + " milliseconds");

        System.out.println("Time taken to process request for:" + path + " is:" + serviceTime + " milliseconds");

    }
}
